package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.common.entity.EasyUIDatagridResult;
import cn.itcast.bos.common.utils.PinYin4jUtils;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.AreaService;

/**
 * 区域模块
 * 
 * @author Beck
 *
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private AreaService areaService;

	// 获取上传进来的文件
	private File myFile;

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	/**
	 * 批量导入区域信息
	 */
	@Action(value = "areaAction_import", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/area.html") })
	public String importArea() throws Exception {
		List<Area> areaList = new ArrayList<Area>();
		// 读取xml文件
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(myFile));
		HSSFSheet sheet = workbook.getSheetAt(0);
		// 遍历行
		for (Row row : sheet) {
			if (row.getRowNum() == 0) {
				// 标题直接跳过
				continue;
			}
			// 跳过空值行
			if (row.getCell(0) != null && StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			Area node = new Area();
			// 编号
			String id = row.getCell(0).getStringCellValue();
			node.setId(id);
			// 省
			String province = row.getCell(1).getStringCellValue();
			node.setProvince(province);
			// 城市
			String city = row.getCell(2).getStringCellValue();
			node.setCity(city);
			// 区域
			String district = row.getCell(3).getStringCellValue();
			node.setDistrict(district);
			// 邮编
			String postCode = row.getCell(4).getStringCellValue();
			node.setPostcode(postCode);
			// 简码
			String[] headByString = PinYin4jUtils.getHeadByString(province.substring(0, province.length() - 1)
					+ city.substring(0, city.length() - 1) + district.substring(0, district.length() - 1));
			StringBuffer shortcode = new StringBuffer();
			for (String s : headByString) {
				shortcode.append(s);
			}
			node.setShortcode(shortcode.toString());
			// 城市编码
			String citycode = PinYin4jUtils.hanziToPinyin(city.substring(0, city.length() - 1), "");
			node.setCitycode(citycode);

			areaList.add(node);

		}
		// 保存导入的数据
		areaService.batchImprotArea(areaList);
		return SUCCESS;
	}



	/**
	 * 分页查询
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "areaAction_page", results = { @Result(name = "success", type = "json") })
	public String pageQuery() throws Exception {
		Pageable pageable = new PageRequest(page - 1, rows);
		// 创建查询条件
		Specification<Area> spec = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<>();
				
				// 省份
				if (StringUtils.isNotBlank(model.getProvince())){
					Predicate p = cb.like(root.get("province").as(String.class), "%"+model.getProvince()+ "%");
					predicateList.add(p);
				}
				
				// 城市
				if (StringUtils.isNotBlank(model.getCity())){
					Predicate p = cb.like(root.get("city").as(String.class),  "%"+model.getCity()+ "%");
					predicateList.add(p);
				}
				
				// 区县
				if (StringUtils.isNotBlank(model.getDistrict())){
					Predicate p = cb.like(root.get("district").as(String.class),  "%"+model.getDistrict()+ "%");
					predicateList.add(p);
				}
				
				// 拼接查询条件
				Predicate predicate = null;
				if (predicateList != null && predicateList.size() > 0){
					Predicate[] array = new Predicate[predicateList.size()];
					predicate = cb.and(predicateList.toArray(array));
				}
				
				return predicate;
			}
		};
		Page<Area> areaPage = areaService.findByPage(pageable,spec);
		EasyUIDatagridResult datagridResult = new EasyUIDatagridResult(areaPage.getTotalElements(), areaPage.getContent());
		ActionContext.getContext().getValueStack().push(datagridResult);
		return SUCCESS;
	}

}
